import os
import sys

import qdarkstyle  # 导入 qdarkstyle 模块
from PyQt5 import QtCore, QtWidgets, QtGui
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QWidget

from report.analyze_slaughter_schedule import create_analyze_slaughter_schedule, process_analyze_slaughter_schedule
from report.school_prison_delivery_list import process_school_prison_delivery_list, \
    create_school_prison_delivery_list
from report.super_cater_driver_delivery_table import process_super_cater_driver_delivery_table, \
    create_super_cater_driver_delivery_table
from report.super_cater_order_workshop_table import process_super_cater_order_workshop_table, \
    create_super_cater_order_workshop_table
from report.super_cater_order_workshop_table_add import process_super_cater_order_workshop_table_add, \
    create_super_cater_order_workshop_table_add
from views.main_interface import Ui_Form

from datetime import datetime, timedelta

# 设置起始行为第二行
start_row = 2  # Excel索引从1开始，但这里我们实际上从第二行数据开始处理，所以起始行为1


class MyForm(QWidget, Ui_Form):
    FILE_SELECTION_WARNING = "请选择文件！"
    WRONG_FILE_FORMAT_WARNING = "请选择xls文件或者xlsx文件！"
    PATH_SEPARATOR = '///'  # 定义路径分隔符常量
    ACCEPTED_EXCEL_EXTENSIONS = ('.xls', '.xlsx')
    # 路线对应运货司机
    delivery_driver = {
        '1': '潘金宇',
        '2': '李东华',
        '3': '谭克发',
        '4': '余强',
        '5': '刘烁',
        '51': '刘烁',
        '6': '张道全',
        '7': '张郑州',
        '71': '张郑州',
        '72': '张郑州',
        '8': '胡荣华',
    }
    # 路线对应地点
    driver_route = {
        '1': '枝江城区 问安',
        '2': '安福寺 紫荆岭 貔亭',
        '3': '董市 姚家港 枝江雅斯',
        '4': '仙女 奥美 江口 七星台',
        '5': '荆州天天',
        '6': '白洋 顾家店',
        '7': '荆州好邻居 永汇',
        '8': '百里洲 州哥卤菜 曹师付',
    }

    def __init__(self) -> None:
        super(MyForm, self).__init__()
        self.setupUi(self)
        self.file_path = ''
        self.file_path2 = ''
        # self.setAcceptDrops(True)
        self.signal_slot()

        # 获取当前脚本的绝对路径
        current_path = os.path.abspath(__file__)
        # print("当前脚本路径:", current_path)

        # 获取当前脚本所在目录的绝对路径
        script_directory = os.path.dirname(current_path)
        # print("当前脚本所在目录:", script_directory)

        icon_filename = 'favicon3.ico'
        resource_subdir = 'resources_rc'

        # 使用os.path.join()来拼接路径，确保跨平台兼容性
        full_icon_path = os.path.join(script_directory, resource_subdir, icon_filename)

        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(full_icon_path), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.setWindowIcon(icon)

        # 将字典转换为字符串并设置给textEdit_3
        delivery_driver_info = '\n'.join([f"{key}: {value}" for key, value in self.delivery_driver.items()])
        self.textEdit_3.setText(delivery_driver_info)

        # 将字典转换为字符串并设置给textEdit_4
        driver_route_info = '\n'.join([f"{key}: {value}" for key, value in self.driver_route.items()])
        self.textEdit_4.setText(driver_route_info)

    # 定义信号槽
    def signal_slot(self):
        # 检查是否过期
        if self.is_expired():
            self.textEdit.setText("代码已过期，请联系开发者更新！")
            # print("代码已过期，请联系开发者更新！")
            return

        # 读取本地文件
        self.pushButton_5.clicked.connect(self.read_local_xls)
        self.pushButton_6.clicked.connect(self.read_local_xls2)

        # Supermarket Catering (Workshop Distribution Table)
        # 商超餐饮(车间配货表)
        self.pushButton.clicked.connect(self.action_super_cater_order_workshop_table)

        # 商超餐饮(司机送货表)
        self.pushButton_3.clicked.connect(self.action_super_cater_driver_delivery_table)

        # 商超餐饮(加单表)
        self.pushButton_7.clicked.connect(self.action_super_cater_order_workshop_table_add)

        # School Prison (Delivery List)
        # 学校(配货表)(送货表)
        self.pushButton_2.clicked.connect(self.action_school_prison_delivery_list)

        # 分析屠宰计划表
        # Analyze slaughter schedule
        self.pushButton_4.clicked.connect(self.action_analyze_slaughter_schedule)

    def is_expired(self):
        # 定义代码的有效期截止日期（从代码编写日期起算一个月）
        start_date = datetime(2025, 7, 24)  # 代码编写日期
        expiration_date = start_date + timedelta(days=30)  # 一个月后过期
        current_date = datetime.now()

        # 检查是否过期
        if current_date > expiration_date:
            return True
        return False

    def read_local_xls(self):
        filePath, _ = QtWidgets.QFileDialog.getOpenFileName(self, '选择XLS文件', '',
                                                            'Excel Files (*.xls *.xlsx);;All Files (*)')
        if filePath != '':
            try:
                self.textEdit.setText(filePath)

            except Exception as e:
                QtWidgets.QMessageBox.critical(self, "错误", f"读取文件时发生错误: {str(e)}")

    def read_local_xls2(self):
        filePath, _ = QtWidgets.QFileDialog.getOpenFileName(self, '选择XLS文件', '',
                                                            'Excel Files (*.xls *.xlsx);;All Files (*)')
        if filePath != '':
            try:
                self.textEdit_2.setText(filePath)

            except Exception as e:
                QtWidgets.QMessageBox.critical(self, "错误", f"读取文件时发生错误: {str(e)}")

    def text_to_dict(self):
        """将特定格式的文本转换为字典"""
        # 使用换行符分割每一行，然后对每一行使用等号分割键和值
        text = self.textEdit_3.toPlainText()
        lines = text.split('\n')
        result_dict = {}
        for line in lines:
            if ':' in line:  # 确保这一行包含等号，即是一个键值对
                key, value = line.split(':', 1)  # 通过=分割成键和值，1代表只分割第一次出现的=
                result_dict[key.strip()] = value.strip()  # 去除前后空格并存入字典
        return result_dict

    # 商超餐饮(车间配货表)
    def action_super_cater_order_workshop_table(self):
        dict1 = self.delivery_driver
        dict2 = self.text_to_dict()
        if dict1 != dict2:
            self.delivery_driver = dict2
        all_datas = process_super_cater_order_workshop_table(self)
        create_super_cater_order_workshop_table(self, all_datas)

    # 商超餐饮(司机送货表)
    def action_super_cater_driver_delivery_table(self):
        dict1 = self.delivery_driver
        dict2 = self.text_to_dict()
        if dict1 != dict2:
            self.delivery_driver = dict2
        all_datas, field_list = process_super_cater_driver_delivery_table(self)
        create_super_cater_driver_delivery_table(self, all_datas, field_list)

    # Supermarket Catering (Additional Order Form)
    # 商超餐饮(加单表)
    def action_super_cater_order_workshop_table_add(self):
        dict1 = self.delivery_driver
        dict2 = self.text_to_dict()
        if dict1 != dict2:
            self.delivery_driver = dict2
        all_datas = process_super_cater_order_workshop_table_add(self)
        create_super_cater_order_workshop_table_add(self, all_datas)

    # 学校(配货表)(送货表)
    def action_school_prison_delivery_list(self):
        all_datas = process_school_prison_delivery_list(self)
        create_school_prison_delivery_list(self, all_datas)

    # 分析屠宰计划表
    # Analyze slaughter schedule
    def action_analyze_slaughter_schedule(self):
        dict1 = self.delivery_driver
        dict2 = self.text_to_dict()
        if dict1 != dict2:
            self.delivery_driver = dict2
        all_datas = process_analyze_slaughter_schedule(self)
        create_analyze_slaughter_schedule(self, all_datas)


if __name__ == "__main__":
    # 高清屏幕自适应
    QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
    # 固定的，PyQt5程序都需要QApplication对象。sys.argv是命令行参数列表，确保程序可以双击运行
    app = QApplication(sys.argv)
    # app.setStyle("Fusion")
    app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())
    # 初始化
    myWin = MyForm()
    # 将窗口控件显示在屏幕上
    myWin.show()
    # 程序运行，sys.exit方法确保程序完整退出。
    sys.exit(app.exec_())
